package org.lucene;

import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.util.BytesRef;

public class MySimilarity extends DefaultSimilarity {

	// 这里表示每一个Document中所有匹配的关键字与当前关键字的匹配比例因素影响,同理也不考滤.
	@Override
	public float coord(int overlap, int maxOverlap) {
		return super.coord(overlap, maxOverlap);
	}

	@Override
	public float queryNorm(float sumOfSquaredWeights) {
		return super.queryNorm(sumOfSquaredWeights);
	}

	// term freq 表示 term 在一个document的出现次数,这里设置为1.0f表示不考滤这个因素影响
	@Override
	public float tf(float freq) {
//		return (float)Math.sqrt(freq);
		return 1.0f;
	}

	// 这里表示匹配的docuemnt在全部document的影响因素,同理也不考滤
	@Override
	public float idf(long docFreq, long numDocs) {
		// return (float)(Math.log(numDocs/(double)(docFreq+1)) + 1.0);
		return 1.0f;
	}

	@Override
	public float lengthNorm(FieldInvertState state) {
	    final int numTerms;
	    if (discountOverlaps)
	      numTerms = state.getLength() - state.getNumOverlap();
	    else
	      numTerms = state.getLength();
	   return state.getBoost() * ((float) (1.0 / Math.sqrt(numTerms)));
	}
	

	// 这里表示匹配的 term　与 term之间的距离因素,同样也不应该受影响
	@Override
	public float sloppyFreq(int distance) {
		return super.sloppyFreq(distance);
	}

	@Override
	public float scorePayload(int doc, int start, int end, BytesRef payload) {
		return super.scorePayload(doc, start, end, payload);
	}

	protected boolean discountOverlaps = true;

	/**
	 * Determines whether overlap tokens (Tokens with 0 position increment) are
	 * ignored when computing norm. By default this is true, meaning overlap
	 * tokens do not count when computing norms.
	 * 
	 * @lucene.experimental
	 * 
	 * @see #computeNorm
	 */
	public void setDiscountOverlaps(boolean v) {
		discountOverlaps = v;
	}

	/**
	 * Returns true if overlap tokens are discounted from the document's length.
	 * 
	 * @see #setDiscountOverlaps
	 */
	public boolean getDiscountOverlaps() {
		return discountOverlaps;
	}

	@Override
	public String toString() {
		return "DefaultSimilarity";
	}

}